package com.wanwu.channel.controller;

import com.alibaba.fastjson.JSONObject;
import com.wanwu.channel.biz.PayOrderService;
//import com.wanwu.channel.config.WxPayConfig;
import com.wanwu.channel.util.HttpUtils;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import com.wechat.pay.java.core.http.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 确认收货
 */
@RestController
@Slf4j
public class PayNotifyController {

//    @Autowired
//    private WxPayConfig wxPayConfig;
    @Autowired
    private PayOrderService payOrderService;

    @PostMapping("/wechatpay/result")
    @ResponseBody
    public ResponseEntity.BodyBuilder wechatpayResult(HttpServletRequest request, HttpServletResponse response) {

        try {

            //处理通知参数
            String body = HttpUtils.readData(request);
            log.info("微信支付结果回调参数：{}", body);

            //回调通知的验签与解密
            String wechatPaySerial = request.getHeader(Constant.WECHAT_PAY_SERIAL);
            // 请求头Wechatpay-Nonce
            String nonce = request.getHeader(Constant.WECHAT_PAY_NONCE);
            // 请求头Wechatpay-Timestamp
            String timestamp = request.getHeader(Constant.WECHAT_PAY_TIMESTAMP);
            // 请求头Wechatpay-Signature
            String signature = request.getHeader(Constant.WECHAT_PAY_SIGNATURE);

            // 构造 RequestParam
            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(wechatPaySerial)
                    .nonce(nonce)
                    .signature(signature)
                    .timestamp(timestamp)
                    .body(body)
                    .build();

            // 以支付通知回调为例，验签、解密并转换成 Transaction
//            Transaction transaction = wxPayConfig.getParser().parse(requestParam, Transaction.class);


        } catch (Exception e) {
            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
            log.error("sign verification failed", e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED);
        }

        return ResponseEntity.status(HttpStatus.OK);
    }
}